package com.zxy.supplier_system.server.entity

import jakarta.persistence.*
import org.hibernate.annotations.SQLRestriction
import org.springframework.data.annotation.CreatedBy
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.time.OffsetDateTime

@Entity
@EntityListeners(AuditingEntityListener::class)
@Table(
    uniqueConstraints = [UniqueConstraint(
        columnNames = ["account_id", "year", "month"]
    )]
)
@SQLRestriction("year >= 1900 AND year <= 2100 AND month >= 1 AND month <= 12")
class MarketSaleDocument {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long = 0

    @CreatedDate
    lateinit var createdDateTime: OffsetDateTime

    @CreatedBy
    @ManyToOne(optional = false)
    @JoinColumn(nullable = false)
    lateinit var createdBy: Employee

    @OneToMany(orphanRemoval = true, mappedBy = "document", cascade = [CascadeType.ALL])
    @OrderBy(value = "sequence asc")
    var goodsList: MutableList<MarketSaleDocumentItem> = mutableListOf()

    var auditedDateTime: OffsetDateTime? = null

    var submittedDateTime: OffsetDateTime? = null

    var month: Int = 1

    var year: Int = 0

    @get:Transient
    val market: Market
        get() = account.market

    @ManyToOne(optional = false)
    @JoinColumn(nullable = false)
    lateinit var account: MarketAccount

    enum class Status {
        WAIT_SUBMIT,
        SUBMITTED,
        VALIDATED,
    }

    @get:Transient
    val status: Status
        get() {
            return if (submittedDateTime == null) {
                Status.WAIT_SUBMIT
            } else if (auditedDateTime == null) {
                Status.SUBMITTED
            } else {
                Status.VALIDATED
            }
        }

    var note: String? = null

}